// Echo4 prints its command-line arguments.
package main

import (
	"flag"
	`fmt`
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	`sync`
	"time"
)

var bigValue = "123123123123123123123123123123123123123123123123123123123123"

type User struct {
	// 设置主键
	ID uint `gorm:"primary_key"`
	// 设置特定类型
	Introduction string `gorm:"type:text"`
	// 设置大小
	Role string `gorm:"size:255";sql:"index"`
	S1   string `gorm:"size:255"`
	S2   string `gorm:"size:255"`
	S3   string `gorm:"size:255"`
	S4   string `gorm:"size:255"`
	S5   string `gorm:"size:255"`
	S6   string `gorm:"size:255"`
	//S7 string `gorm:"size:255"`
	//S8 string `gorm:"size:255"`
	//S9 string `gorm:"size:255"`
	// 三个特殊的字段，只要这样声明，就会起到对应的效果
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *time.Time // 因为DeletedAt是一个nullable的字段，而go不支持，所以改用指针类型
}

func main() {
	var n = flag.Int("n", 100, "add n key to redis")
	var ip = flag.String("ip", "127.0.0.1", "MySQL ip address")
	var port = flag.Uint("p", 3306, "MySQL port")
	var user = flag.String("u", "root", "MySQL username")
	var pw = flag.String("pw", "root", "MySQL password")
	var dbName = flag.String("db", "sys", "MySQL database")
	var gCount = flag.Int("g", 10, "the goroutine will be created")
	flag.Parse()

	db, err := getDB(*ip, *port, *user, *pw, *dbName)
	if err != nil {
		fmt.Println(err)
		return
	}

	if !db.HasTable(&User{}) {
		db = db.CreateTable(&User{})
	}
	db.Close()

	wg := sync.WaitGroup{}
	wg.Add(*gCount)
	for i := 0; i < *gCount; i++ {
		go func(n int) {
			db, _ := getDB(*ip, *port, *user, *pw, *dbName)

			for j := 0; j < n; j++ {
				db.Create(&User{Introduction: bigValue, Role: bigValue, S1: bigValue, S2: bigValue, S3: bigValue, S4: bigValue, S5: bigValue, S6: bigValue})
			}

			wg.Done()
		}(*n / *gCount)
	}
	wg.Wait()
}

func getDB(ip string, port uint, user string, pw string, dbName string) (*gorm.DB, error) {
	db, err := gorm.Open("mysql",
		fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", user, pw, ip, port, dbName))
	return db, err
}
